import { AxiosRequestConfig } from "axios";
import { HttpOption, HttpResponse } from "@/interface";
import service from "./service";
import { ERROR_MESSAGE } from "@/common";

/**
 * 响应拦截
 * 定义返回数据类型的泛型 T，默认值是 any
 */
function http<T>({ url: url, obj: { params, data, method, headers, beforeRequest, afterRequest } }: HttpOption) {
  /**
   * 成功处理
   */
  const successHandler = (res: AxiosRequestConfig<HttpResponse<T>>) => {
    if (res.data) {
      if (res.data.code === "ok") {
        return res.data.data;
      } else {
        return Promise.reject(res.data.message);
      }
    } else {
      return Promise.reject(ERROR_MESSAGE);
    }
  };
  /**
   * 失败处理
   */
  const failHandler = (error: HttpResponse<Error>) => {
    /**
     * 请求后执行
     */
    afterRequest && afterRequest();
    return Promise.reject(error.message || ERROR_MESSAGE);
  };
  /**
   * 请求前执行
   */
  beforeRequest && beforeRequest();
  /**
   * 响应处理
   */
  if (method === "GET" || !method) {
    return service.get(url, { params }).then(successHandler, failHandler);
  } else if (method === "POST") {
    return service.post(url, data, { headers: headers }).then(successHandler, failHandler);
  } else if (method === "DELETE") {
    return service.delete(url, { params, data }).then(successHandler, failHandler);
  } else if (method === "PUT") {
    return service.put(url, data, { headers: headers }).then(successHandler, failHandler);
  } else {
    return service.get(url, { params }).then(successHandler, failHandler);
  }
}

/**
 * 响应拦截
 */
function request<T>(url: string, obj: object): Promise<T> {
  return http<T>({
    url: url,
    obj: obj
  });
}

export default request;
